package com.loopj.ohos.image;

import ohos.app.Context;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class WebImage implements SmartImage {
    /**
     * 超时时间
     */
    private static final int CONNECT_TIMEOUT = 5000;
    private static final int READ_TIMEOUT = 8000;

    private static WebImageCache webImageCache;

    private String url;

    /**
     * WebImage的构造方法，获取URL
     *
     * @param url 图片url
     */
    public WebImage(String url) {
        this.url = url;
    }

    /**
     * 获取PixelMap
     *
     * @param context context
     * @return PixelMap
     */
    public PixelMap getBitmap(Context context) {
        // Don't leak context
        if (webImageCache == null) {
            webImageCache = new WebImageCache(context);
        }

        // Try getting bitmap from cache first
        PixelMap bitmap = null;
        if (url != null) {
            bitmap = webImageCache.get(url);
            if (bitmap == null) {
                bitmap = getBitmapFromUrl(url);
                if (bitmap != null) {
                    webImageCache.put(url, bitmap);
                }
            }
        }

        return bitmap;
    }

    /**
     * 根据Url获取网络图片资源
     *
     * @param url 图片url
     * @return PixelMap
     */
    private PixelMap getBitmapFromUrl(String url) {
        try {
            URLConnection conn = new URL(url).openConnection();
            conn.setConnectTimeout(CONNECT_TIMEOUT);
            conn.setReadTimeout(READ_TIMEOUT);
            InputStream is = conn.getInputStream();
            ImageSource source = ImageSource.create(is, new ImageSource.SourceOptions());
            ImageSource.DecodingOptions options = new ImageSource.DecodingOptions();
            PixelMap pixelMap = source.createPixelmap(options);
            is.close();
            return pixelMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 提供移除缓存的方法
     *
     * @param url 图片url
     */
    public static void removeFromCache(String url) {
        if (webImageCache != null) {
            webImageCache.remove(url);
        }
    }
}
